package user

import (
	"sanguo/node/common/asynwrap"
	"sanguo/node/common/transaction"
	"sanguo/node/common/db"
	cs_message "sanguo/protocol/cs/message"
	"time"
	"github.com/go-redis/redis"
	"github.com/golang/protobuf/proto"
)

const (
	load_ok      = 1
	load_timeout = 2
	load_error   = 3
)

type transactionLoad struct {
	transaction.TransactionBase
	user    *User
	errcode int
}

func (this *transactionLoad) GetModuleName() string {
	return "Load"
}

func (this *transactionLoad) GetReplyMsg() proto.Message {
	return nil
}

func (this *transactionLoad) SetExpiredTime(expired time.Time) {
	this.Expired = expired
}

func (this *transactionLoad) GetExpiredTime() time.Time {
	return this.Expired
}

func (this *transactionLoad) Begin() {
	key := "role:" + this.user.userID

	asynwrap.Wrap(db.GetRedisClient("game").HGetAll)(func(ret []interface{}) {
		result, err := ret[0].(*redis.StringStringMapCmd).Result()
		if err != nil {
			this.errcode = load_error
			this.user.EndTrans(this)
		}

		role := this.user.GetModuleByName("role")

		if nil == role {
			this.errcode = load_error
			this.user.EndTrans(this)
		}

		if !role.Init(result) {
			this.errcode = load_error
		} else {
			this.errcode = load_ok
		}
		this.user.EndTrans(this)
	}, key)
}

func (this *transactionLoad) End() {
	if this.errcode == load_ok {
		this.user.loginOK()
	} else {
		onLoginError(this.user, this.user.session, cs_message.EnumType_LOGIN_ERROR)
	}
}

func (this *transactionLoad) Timeout() {
	this.errcode = load_timeout
	this.user.EndTrans(this)
}

func (this *User) load() {
	this.transMgr.PushTrans(&transactionLoad{
		user: this,
	}, time.Second*10)
}
